package com.ruoyi.web.controller.module.employee;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.employee.domain.EmployeeApply;
import com.ruoyi.employee.domain.EmployeeUser;
import com.ruoyi.employee.service.IEmployeeApplyService;
import com.ruoyi.employee.service.IEmployeeUserService;
import com.ruoyi.market.domain.ConfigEmployee;
import com.ruoyi.market.service.IConfigEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户申请店员信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/employee/apply")
public class EmployeeApplyController extends BaseController
{
    @Autowired
    private IEmployeeApplyService employeeApplyService;

    @Autowired
    private IEmployeeUserService employeeUserService;

    @Autowired
    private IConfigEmployeeService configEmployeeService;

    /**
     * 获取用户申请店员列表
     */
    @PreAuthorize("@ss.hasPermi('employee:apply:list')")
    @PostMapping("/employeeApplyList")
    public TableDataInfo list(@RequestBody EmployeeApply employeeApply, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            employeeApply.setShopId(shopId);
        }
        startPageByPost();
        List<EmployeeApply> list = employeeApplyService.selectUserList(employeeApply);
        return getDataTable(list);
    }

    /**
     * 根据用户申请店员编号获取详细信息
     */
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        EmployeeApply employeeApply = employeeApplyService.selectUserById(userId);
        ajax.put(AjaxResult.DATA_TAG, employeeApply);
        return ajax;
    }

    /**
     * 申请店员编号获取详细信息
     */
    @GetMapping("/employeeApplyInfo")
    public AjaxResult employeeApplyInfo()
    {
        AjaxResult ajax = AjaxResult.success();
        Long employeeId = SecurityUtils.getUserId();
        EmployeeApply ea = employeeApplyService.selectUserByEmployeeId(employeeId);
        ajax.put(AjaxResult.DATA_TAG, ea);
        return ajax;
    }

    /**
     * 店员资料编辑 - 客户修改
     */
    @PostMapping("/employeeApplyInfoEdit")
    public AjaxResult employeeApplyInfoEdit(@Validated @RequestBody EmployeeApply user)
    {
        // 当前登录用户
        Long userId = SecurityUtils.getUserId();
        EmployeeUser eu = new EmployeeUser();
        eu.setUserId(userId);
        eu.setPhonenumber(user.getPhonenumber());
        eu.setNickName(user.getNickName());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !employeeUserService.checkPhoneUnique(eu))
        {
            return error("提交资料修改：店员'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getNickName()) && !employeeUserService.checkNickNameUnique(eu))
        {
            return error("提交资料修改：店员'" + user.getUserName() + "'失败，昵称已存在");
        }
        EmployeeApply ea = employeeApplyService.selectUserByEmployeeId(userId);
        if(StringUtils.isNotNull(ea)){
            return error("提交资料修改：店员'" + user.getUserName() + "'失败，存在审核中的数据");
        }
        user.setEmployeeId(userId);

        ConfigEmployee configEmployee = configEmployeeService.selectConfigEmployeeByShopId(user.getShopId());
        // 资料修改是否需要审核 Y-是 N-否
        if(configEmployee != null && configEmployee.getStatusInfoAudit().equals(UserConstants.NO)){
            EmployeeUser employeeUser = employeeUserService.selectUserById(user.getEmployeeId());
            employeeUser.setNickName(user.getNickName());
            employeeUser.setWxId(user.getWxId());
            employeeUser.setAvatar(user.getAvatar());
            employeeUser.setImages(user.getImages());
            employeeUser.setAddress(user.getAddress());
            employeeUser.setAddressCode(user.getAddressCode());
            employeeUser.setServiceType(user.getServiceType());
            employeeUser.setTags(user.getTags());
            employeeUser.setUserProfile(user.getUserProfile());
            employeeUser.setSpeech(user.getSpeech());
            // 修改店员资料
            employeeUserService.updateUser(employeeUser);
        }else{
            employeeApplyService.insertUser(user);
        }
        AjaxResult ajax = AjaxResult.success();
        return ajax;
    }

    /**
     * 新增用户申请店员
     */
    @PostMapping("/employeeApplyAdd")
    public AjaxResult add(@Validated @RequestBody EmployeeApply user, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            user.setShopId(shopId);
        }
        if (!employeeApplyService.checkCustomerIdUnique())
        {
            return error("新增用户申请店员'" + user.getUserName() + "'失败，请勿重复提交");
        }
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        EmployeeUser eu = new EmployeeUser();
        eu.setUserId(userId);
        eu.setPhonenumber(user.getPhonenumber());
        eu.setNickName(user.getNickName());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !employeeUserService.checkPhoneUnique(eu))
        {
            return error("新增用户申请店员'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getNickName()) && !employeeUserService.checkNickNameUnique(eu))
        {
            return error("新增用户申请店员'" + user.getUserName() + "'失败，昵称已存在");
        }
        return toAjax(employeeApplyService.insertUser(user));
    }

    /**
     * 更新用户申请店员 - 状态的变更
     */
    @PreAuthorize("@ss.hasPermi('employee:apply:edit')")
    @PostMapping("/updateUserStatus")
    public AjaxResult updateUserStatus(@Validated @RequestBody EmployeeApply user)
    {
        if (!employeeApplyService.checkUserStatusIsAudit(user))
        {
            return error("修改用户申请店员'" + user.getUserName() + "'失败，用户不存在或者状态非审核中");
        }
        if (user.getStatus().equals(UserConstants.STATUS_APPROVE) || user.getStatus().equals(UserConstants.STATUS_REJECT))
        {
            user.setUpdateBy(getUsername());
        }else{
            return error("修改用户申请店员'" + user.getUserName() + "'失败，状态传值错误");
        }
        return toAjax(employeeApplyService.updateUserStatus(user));
    }


    /**
     * 修改用户申请店员 - 后台修改
     */
    @PreAuthorize("@ss.hasPermi('employee:apply:edit')")
    @Log(title = "用户申请店员管理 - 修改", businessType = BusinessType.UPDATE)
    @PostMapping("/employeeApplyUpdate")
    public AjaxResult edit(@Validated @RequestBody EmployeeApply user)
    {
        if (!employeeApplyService.checkUserNameUnique(user))
        {
            return error("修改用户申请店员'" + user.getUserName() + "'失败，用户名已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !employeeApplyService.checkPhoneUnique(user))
        {
            return error("修改用户申请店员'" + user.getUserName() + "'失败，手机号码已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(employeeApplyService.updateUser(user));
    }

    /**
     * 删除用户申请店员
     */
    @PreAuthorize("@ss.hasPermi('employee:apply:remove')")
    @Log(title = "用户申请店员管理 - 删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(employeeApplyService.deleteUserByIds(userIds));
    }

    @Log(title = "用户申请店员管理 - 导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('employee:apply:export')")
    @PostMapping("/employeeApplyExport")
    public void export(HttpServletResponse response, EmployeeApply user)
    {
        List<EmployeeApply> list = employeeApplyService.selectUserList(user);
        ExcelUtil<EmployeeApply> util = new ExcelUtil<EmployeeApply>(EmployeeApply.class);
        util.exportExcel(response, list, "用户申请店员数据");
    }
}
